//
//  RJCheckDataVC.m
//  AirQuality
//
//  Created by Po on 15/3/16.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckDataVC.h"
#import "RJCheckDataModel.h"
//#import "RJCheckDataTopTableVC.h"
#import "RJCheckDataBottomTableVC.h"
#import "RJCheckDataSelectView.h"
#import "RJCheckDataTypeSegment.h"
#import "RJCheckDataFitCell.h"
#import "RJCheckBottomView.h"
#import "RJCheckBottomView.h"
#import "RJCheckProvinceModel.h"
#import "RJCheckSendVC.h"
#import "RJCheckVC.h"
#import "RJCheckBottomCell.h"


#import "RJTools.h"

@interface RJCheckDataVC () <RJCheckDataSelectViewDelegate, RJCheckDataTypeSegmentDelegate, RJCheckDataBottomTableDelegate,RJCheckBottomViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *topView;                   //上部表格(统计表格)
@property (weak, nonatomic) IBOutlet UIView *bottomView;                //下部表格（详细信息）
@property (weak, nonatomic) IBOutlet UIView *segmentView;

@property (retain, nonatomic) RJCheckSendVC * sendCheckVC;                  //提交审核

@property (strong, nonatomic)UIImageView * selectView ;

@property (retain, nonatomic) UIView * bottomSectionView;               //下方表头
@property (retain, nonatomic) RJCheckBottomView * bottomTableView;               //下方详情视图

//@property (retain, nonatomic) RJCheckDataTopTableVC * topTableVC;
@property (retain, nonatomic) RJCheckDataBottomTableVC * bottomTableVC;
@property (retain, nonatomic) RJCheckDataTypeSegment * typeSegment;     //展示类型（问题数据）
@property (retain, nonatomic) RJLoadView * myLoadView;                  //加载动画

@property (retain, nonatomic) RJCheckDataModel * model;

@property (retain, nonatomic) RJCheckBottomView * leftView;               //下方详情视图
@property (retain, nonatomic) UITableView * tableView;      //城市信息列表
@property (assign)             BOOL showTable , upProblomData;
@property (strong, nonatomic) UIButton * detailButton;
@property (assign, nonatomic) NSInteger sendProblemCount,problemData;

- (void)initInterface;
@end

@implementation RJCheckDataVC

- (instancetype)initWithData:(NSDictionary *)data title:(NSString *)title data:(NSArray *)dataArray selectRow:(NSInteger)row
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGetData) name:@"didGetData" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGetNoData) name:@"didGetNoData" object:nil];
        _stationCode = data[@"stationCode"];
        _titleString = title;
        _leftModel = dataArray;
        NSDictionary * dic = dataArray[row];
        NSString * stationTypeCode = dic[@"STATIONTYPEID"];
        NSString * stationCode = dic[@"STATIONCODE"];
        NSString * cityCode = dic[@"CITYCODE"];
        NSUserDefaults *userDefailt = [NSUserDefaults standardUserDefaults];
        NSString *userName = [userDefailt objectForKey:@"userName"];
        NSString * status = [RJUserData defaultRJUserData].isProvince ? @"1":@"2";
        _request = @{
                                   @"stationtypecode":stationTypeCode,
                                   @"status":status,     //上传
                                   @"stationcode":stationCode,
                                   @"citycode":cityCode,
                                   @"timepoint":[RJTools getTimeWithFormat:@"yyyy-MM-dd 00:00:00" time:YesterdayDate],
                                   @"userName":userName
                                   };
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proplemData:) name:@"CheckProplemCount" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendCheckProplemData:) name:@"sendCheckProplemData" object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self getLeftData];
    self.navBar.isOtherReturnButton = NO;
    [self.navBar setReturnButtonHidden:NO];
    _showTable = NO;
//    [self.navBar.returnButton setBackgroundImage:[UIImage imageNamed:@"returnBtn"] forState:UIControlStateNormal];
//    CGRect rect = [RJTools getReSizeRect:self.navBar.returnButton.frame size:-5];
//    rect.origin.x -= 5;
//    [self.navBar.returnButton setFrame:rect];
    
    UIButton * button = [self.navBar getRightButton];
    [button setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [button setImageEdgeInsets:UIEdgeInsetsMake(15+3+1, 10+6+1, 10+3+1, 15+6+1)];
    [button addTarget:self action:@selector(pressSelectButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:[self getMyLoadView]];
    _model = [[RJCheckDataModel alloc] initWithStationCode:_stationCode freeStatus:NO];
    _model.topTitle = _titleString;
//    [self netRequsetAllCityAndStation];
  
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    /**更新数据*/
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCityAirData" object:nil userInfo:nil];
     [_selectView removeFromSuperview];
}
#pragma mark - user-defined initialization function
- (void)initInterface
{
    [self initTitle];
    
//    [self getTopTableVC];
    [self getTypeSegment];
    NSArray * array = @[@"SO₂",@"NO₂",@"CO",@"O₃",@"PM₁₀",@"PM"];
    [self getBottomTableSectionViewWithTitles:array];
    [self getBottomTableVC];
    [self initButton];
}

- (void)initButton{
    _detailButton = [[UIButton alloc] init];
    _detailButton.frame = CGRectMake(0, ScreenHeight-235, 35, 35);
    _detailButton.backgroundColor = [UIColor grayColor];
    _detailButton.alpha = 0.5;
    [_detailButton setTitle:@"站点" forState:UIControlStateNormal];
    _detailButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_detailButton addTarget:self action:@selector(showBottomTable:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_detailButton];
}

- (void)initTitle
{
    [self.navBar.centerCityLabel setText:_model.topTitle];
//    [self.navBar.centerTimeLabel setText:[RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate]];
}

- (void)setToptitle:(NSString *)toptitle
{
    [self.navBar.centerCityLabel setText:toptitle];
}

- (RJLoadView *)getMyLoadView
{
    if (!_myLoadView) {
        CGRect rect = self.view.bounds;
        rect.origin.y += 50;
        rect.size.height -= 50;
        _myLoadView = [[RJLoadView alloc] initWithFrame:rect];
    }
    return _myLoadView;
}

- (RJCheckDataTypeSegment *)getTypeSegment
{
    if(!_typeSegment) {
        CGRect rect = CGRectMake(0, 0, ScreenWidth, 40);
        _typeSegment = [[RJCheckDataTypeSegment alloc] initWithFrame:rect];
        [_typeSegment setDelegate:self];
        [self.segmentView addSubview:_typeSegment];
    }
    return _typeSegment;
}

//- (RJCheckDataTopTableVC *)getTopTableVC
//{
//    if (!_topTableVC) {
//        _topTableVC = [[RJCheckDataTopTableVC alloc] init];
//        [_topTableVC.view setFrame:_topView.bounds];
//        [_topView addSubview:_topTableVC.view];
//        [self addChildViewController:_topTableVC];
//    }
//    return _topTableVC;
//}

- (UIView *)getBottomTableSectionViewWithTitles:(NSArray *)titles
{
    if (!_bottomSectionView) {
//        [_bottomView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"HomeSGBack"]]];
//        NSArray * tittles = @[@"时间",@"PM2.5",@"PM10", @"O₃",@"SO₂",@"NO₂",@"CO"];
        CGRect rect = _bottomView.bounds;
        rect.origin.y = 0;
        rect.size.height = 0;
        rect.size.width = ScreenWidth;
        _bottomSectionView = [[UIView alloc] initWithFrame:rect];
        //重置大小
        UIView * topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
        topLine.center = _bottomSectionView.center;
        topLine.backgroundColor = [UIColor grayColor];
        topLine.alpha = 0.5;
        _bottomSectionView.backgroundColor = GetRGBColor(85, 85, 85, 1);
        [_bottomSectionView addSubview:topLine];
        RJCheckDataFitCell * cell = [[RJCheckDataFitCell alloc] initWithFrame:rect buttonNum:titles.count + 1];
        [cell setBackgroundColor:[UIColor clearColor]];
        //设置样式
        [cell setAllFont:[UIFont systemFontOfSize:18]];
        [cell setAllEfficacy:NO];
        for (NSUInteger i = 0; i < titles.count + 1; i ++) {
            RJCheckDataCellButton * button = cell.allButtons[i];
            if (i == 0) {
                NSString * timeString =  (titles.count == 0) ? @"暂无可疑数据" : @"时间";
                [button setTitle:timeString forState:UIControlStateNormal];
                continue;
            }
            [button setTitle:[self getTrueKey:titles[i - 1]] forState:UIControlStateNormal];
            if ([button.titleLabel.text isEqualToString:@"PM"]) {
                CGFloat buttonWidth = button.frame.size.width;
                CGFloat height = button.frame.size.height;
                UILabel * pmLable  = [[UILabel alloc] init];
                pmLable.text = @"2.5";
                pmLable.frame = CGRectMake(buttonWidth/2+11, height/3+3, 20, 20);
//                pmLable.textColor = [UIColor blackColor];
                pmLable.font = [UIFont boldSystemFontOfSize:9];
                [button addSubview:pmLable];
            }
        }
        [_bottomSectionView addSubview:cell];
        //下划线
        UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, ScreenWidth , 0.5)];
        lineView.alpha = 0.5;
        lineView.backgroundColor = [UIColor grayColor];
        UIView * topLine1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
        topLine1.backgroundColor = [UIColor grayColor];
        [_bottomView addSubview:topLine1];
        [_bottomSectionView addSubview:lineView];
        [_bottomView addSubview:_bottomSectionView];
        [_bottomSectionView setBackgroundColor:GetRGBColor(245, 245, 245, 1)];
    }
    return nil;
}

- (NSString *)getTrueKey:(NSString *)key
{
    NSDictionary * dic = @{@"pm2_5":@"PM",@"pm10":@"PM₁₀",@"o3":@"O₃",@"so2":@"SO₂",@"no2":@"NO₂",@"co":@"CO"};
    return (dic[key] == nil ? key : dic[key]);
}

- (RJCheckDataBottomTableVC *)getBottomTableVC
{
    if (!_bottomTableVC) {
        CGRect rect = _bottomView.bounds;
        rect.size.height -= 44;
        rect.origin.y += 44;
        _bottomTableVC = [[RJCheckDataBottomTableVC alloc] init];
        [_bottomTableVC setStationCode:_stationCode];
        [_bottomTableVC setStationName:_model.topTitle];
        [_bottomTableVC.view setFrame:rect];
        [_bottomView addSubview:_bottomTableVC.view];
        [_bottomTableVC setDelegate:self];
        [self addChildViewController:_bottomTableVC];
    }
    return _bottomTableVC;
}

#pragma mark -- 选择上传
- (void)pressSelectButton:(UIButton *)sender
{
    if (_selectView) {
        [_selectView removeFromSuperview];
        _selectView = nil;
        return;
    }
   _selectView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-90, 40, 115-30, 144-60)];
//    _selectView.layer.borderColor = [UIColor blackColor].CGColor;
//    _selectView.layer.borderWidth = 2.0;
//    _selectView.backgroundColor = [UIColor whiteColor];
    _selectView.image = [UIImage imageNamed:@"Rectangle 40"];
    _selectView.userInteractionEnabled = YES;
    [sysWindow addSubview:_selectView];
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 35+5, 115-25, 1)];
    lineView.backgroundColor = [UIColor grayColor];
    [_selectView addSubview:lineView];
    NSString * imageStr = [RJUserData defaultRJUserData].isProvince?@"download":@"update";
    NSArray * imageArr = @[@"filter",imageStr];
    NSString * sendStr = [RJUserData defaultRJUserData].isProvince ? @"下发":@"上传";
    NSArray * titleArray = @[@"筛选",sendStr];
    for (NSInteger i = 0; i < titleArray.count; i ++) {
        UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*40+10, 21, 20)];
        image.image = [UIImage imageNamed:imageArr[i]];
        UIButton * button = [[UIButton alloc] init];
        button.frame = CGRectMake(15, i*40+4, _selectView.frame.size.width, 35);
        [button setTitleColor:GetRGBColor(153, 153, 153, 1) forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        button.tag = i;
        [button addTarget:self action:@selector(twoSegement:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [_selectView addSubview:button];
        [_selectView addSubview:image];
    }
//    [self chooseEvent];
}

- (void)twoSegement:(UIButton *)sender{
    switch (sender.tag) {
        case 0:[self chooseEvent];break;
        case 1:[self uploadData]; break;
        default:
            break;
    }
}

- (void)proplemData:(NSNotification *)notification{
    NSString *string = notification.object;
    self.sendProblemCount = [string integerValue];

}

- (void)sendCheckProplemData:(NSNotification *)notification{
     NSString *string = notification.object;
     self.problemData = [string integerValue];
}
- (void)uploadData{
    
//    NSInteger index = _sendProblemCount + _problemData;
//    if (index != 0) {
//        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据尚未审核完成，请审核数据！" delegate:@"取消" cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alertView show];
//        return;
//    }
    NSString * url = [RJUserData defaultRJUserData].isProvince ? [NetURL defaultURL].SendMessageToCity :[NetURL defaultURL].sendCheck;
    [RJNetWork myNetRequestWithAddress1:url data:_request completeBlock:^(id responseObject) {
        if ([RJUserData defaultRJUserData].isProvince) {
            NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
            if ([status isEqualToString:@"-1"]) {
                [RJTools showTitle:@"失败!" msg:@"数据还未接入" cancelString:@"知道了" vc:self];
            }else if ([status isEqualToString:@"1"]){
                [RJTools showTitle:@"失败!" msg:@"数据已经下发过了,不能重复下发" cancelString:@"知道了" vc:self];
            }else if([status isEqualToString:@"0"]){
                [RJTools showTitle:@"成功!" msg:@"数据下发成功" cancelString:@"知道了" vc:self];
            }else if([status isEqualToString:@"2"]){
                [RJTools showTitle:@"失败!" msg:@"数据下发失败" cancelString:@"知道了" vc:self];
            }else if ([status isEqualToString:@"-2"]){
                [RJTools showTitle:@"失败!" msg:@"参数错误" cancelString:@"知道了" vc:self
                 ];
            }
        }else{
            if (responseObject[@"result"]) {
                NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                if ([status isEqualToString:@"-1"]) {
                    [RJTools showTitle:@"失败" msg:@"数据未接入！" cancelString:@"确定" vc:self];
                }else if ([status isEqualToString:@"0"]){
                    [RJTools showTitle:@"失败" msg:@"还未下发,不能上传！" cancelString:@"确定" vc:self];
                }else if ([status isEqualToString:@"1"]){
                    [RJTools showTitle:@"失败" msg:@"已上传,不能重复上传！" cancelString:@"确定" vc:self];
                }else if ([status isEqualToString:@"2"]){
                    [RJTools showTitle:@"成功" msg:@"上传数据成功！" cancelString:@"知道了" vc:self];
                }else if ([status isEqualToString:@"3"]){
                    [RJTools showTitle:@"失败" msg:@"上传数据失败，请重试！" cancelString:@"确定" vc:self];
                }
            }
        }
    }failBlack:^(id response) {
        [RJTools showTitle:@"失败" msg:@"上传数据出现错误！" cancelString:@"知道了" vc:self];
    }];


}
- (void)chooseEvent{
    
        RJCheckDataSelectView * selectView = [[RJCheckDataSelectView alloc] initWithTitles:@[@"PM2.5",@"PM10",@"O3",@"SO2",@"NO2",@"CO"]];
        [selectView setSelectTypes:_bottomTableVC.selectKeysArray];
        [selectView setDelegate:self];
        [sysWindow addSubview:selectView];
}

- (void)getLeftData:(NSString *)stationCode{
    
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].stationData data:@{@"stationcode":stationCode,@"timepoint":[RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate]} completeBlock:^(id responseObject) {
        _leftArray = responseObject[@"data"];
    }failBlack:^(id response) {

    }];
    
}

#pragma mark - notification
- (void)positionValueIsGet:(NSNotification *)data
{
    NSLog(@"%@",data.object);
      
}
#pragma mark -- showLeftTable
- (void)showBottomTable:(UIButton *)sender{
    _showTable = !_showTable;
    if (_showTable) {
      [self getTableView];
    }else{
        [_tableView removeFromSuperview];
    }
   
}

- (void)getTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ScreenHeight-200,170, 200)];
    _tableView.dataSource = self;
     _tableView.delegate = self;
    [_tableView setSeparatorColor:[UIColor whiteColor]];
        [self.view addSubview:_tableView];
    [self.view bringSubviewToFront:_tableView];
   
       _showTable = YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdent = @"CheckBottom";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];
    }
    cell.contentView.backgroundColor = [UIColor colorWithRed:177/255.0 green:177/255.0 blue:177/255.0 alpha:0.5];
    cell.textLabel.text = _leftModel[indexPath.row][@"POSITIONNAME"];
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _leftModel.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
            _leftStationCode = _leftModel[indexPath.row][@"STATIONCODE"];
            [self getLeftData:_leftStationCode];
//            NSRange range = [_titleString rangeOfString:@"-"];
//            _titleString = [_titleString substringToIndex:range.location];
//            _titleString = [[_titleString stringByAppendingString:@"- "] stringByAppendingString:_leftModel[indexPath.row][@"POSITIONNAME"] ];
            _titleString = _leftModel[indexPath.row][@"POSITIONNAME"];
            [_bottomTableVC setStationName:_titleString];
            _model = [[RJCheckDataModel alloc] initWithStationCode:_stationCode freeStatus:NO];
            _model.topTitle = _titleString;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [_tableView removeFromSuperview];
              NSArray  *cellKeys = @[@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"];
                if (_leftArray.count == 0) {
                    return ;
                }
                if (!_upProblomData) {
                    [_bottomTableVC setData:_leftArray time:24 cellKeys:cellKeys];
                    [_tableView removeFromSuperview];
                }else{
                    [_bottomTableVC setData1:_leftArray time1:24 cellKeys1:cellKeys];
                    [_tableView removeFromSuperview];
                }
            
            });
            _showTable = NO;
}


#pragma mark RJCheckDataSelectViewDelegate
- (void)CheckDataSelectView:(RJCheckDataSelectView *)selectView didEndSelectWithTitle:(NSArray *)title
{
    if (title.count == 0) {
        [RJTools showTitle:@"提示" msg:@"您没有选择任何指标" cancelString:@"我知道了" vc:self];
    } else {
//        [_topTableVC setCellKeys:title];
        
        if (_bottomTableVC.showProblem) {
            [_bottomTableVC showProblem:NO];
            [_typeSegment setSelectCount:0];
        }
        [_bottomTableVC setCellKeys:title];
    }
}

#pragma mark RJCheckDataTypeSegmentDelegate
- (void)CheckDataTypeSegmentDidSelectCount:(NSUInteger)count type:(NSString *)type
{
     _upProblomData = (count == 0) ? NO : YES;
    [_bottomTableVC showProblem:(count == 0) ? NO : YES];

}

#pragma mark RJCheckDataBottomTableDelegate
- (void)CheckDataBottomTable:(RJCheckDataBottomTableVC *)tableVC showTypes:(NSArray *)types
{
    if (_bottomSectionView) {
        [_bottomSectionView removeFromSuperview];
        _bottomSectionView = nil;
    }
    
    [self getBottomTableSectionViewWithTitles:types];
//    [_topTableVC setCellKeys:types];
}

#pragma mark SuperDelegate
- (void)freeData
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"didGetData" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"didGetNoData" object:nil];
}

#pragma notifaction
- (void)didGetData
{
    [[self getMyLoadView] removeSelf];
    [self initInterface];
//    [_topTableVC setData:_model.data time:24 keys:_model.cellKeys];
    [_bottomTableVC setData:_model.data time:24 cellKeys:_model.cellKeys];
}

- (void)didGetNoData
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"获取数据失败" message:@"请检查网络连接是否正常！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * refresh = [UIAlertAction actionWithTitle:@"刷新" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [_model getStationDataWithStationCode:_stationCode];
    }];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"返回上一页" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:refresh];
    [alert addAction:action];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    NSLog(@"%@",[self.view subviews]);
}
@end
